package com.sicheng.lc.杂题.二分技巧;

/**
 * @author zsc
 * @version 1.0
 * @date 2022/6/24 14:48
 */
@SuppressWarnings("all")
public class 二分技巧 {
    //https://leetcode.cn/problems/binary-search/solution/er-fen-cha-zhao-xiang-jie-by-labuladong/


    int leftBinarySearch(int[] nums, int x) {
        int l = 0, r = nums.length - 1;
        while (l <= r) {
            int mid = l + r >> 1;
            if (nums[mid] >= x) {
                r = mid - 1;
            } else {
                l = mid + 1;
            }
        }
        if (l >= nums.length || nums[l] != x)
            return -1;
        return l;
    }

    int rightBinarySearch(int[] nums, int x) {
        int l = 0, r = nums.length - 1;
        while (l <= r) {
            int mid = l + r >> 1;
            if (nums[mid] <= x) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        if (r < 0 || nums[r] != x)
            return -1;
        return r;

    }
}
